package com.cyh.DynamicReschedularThread;

import java.io.FileInputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Created by yanhuche on 2/21/2017.
 */
public class ThreadRescheduling {


    public static void main(String[] args) {
        new ThreadRescheduling().run();
    }

    private ScheduledExecutorService scheduledExecutorService;
    private ScheduledFuture<?> future;
    private int oldValue = 2;

    private void run() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        future = scheduledExecutorService.scheduleAtFixedRate(new Task(), 0, 2, TimeUnit.SECONDS);
    }

    class Task implements Runnable {

        @Override
        public void run() {
            System.out.println(new Date());
            reschedule();
        }

    }

    private void reschedule() {
        try {
            Path configFilePath = Paths.get(System.getProperty("user.dir"), "Reschedule.txt");
            Properties properties = new Properties();
            properties.load(new FileInputStream(configFilePath.toFile()));
            int sleepSecond = Integer.valueOf(properties.getProperty("sleepSecond"));
            if (sleepSecond != oldValue) {
                if (future != null) {
                    future.cancel(true);
                }
                future = scheduledExecutorService.scheduleAtFixedRate(new Task(), 0, sleepSecond, TimeUnit.SECONDS);
                System.out.println("new interval is: " + sleepSecond);

                oldValue = sleepSecond;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
